<template>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="0" size="large" @keyup.enter="login">
        <el-form-item prop="email">
            <el-input v-model="form.email" prefix-icon="Message" clearable
                      :placeholder="t('login.userPlaceholder')"></el-input>
        </el-form-item>
        <el-form-item prop="password">
            <el-input v-model="form.password" prefix-icon="Lock" clearable show-password
                      :placeholder="t('login.PWPlaceholder')"></el-input>
        </el-form-item>
        <el-form-item prop="captcha" style="margin-bottom: 20px;">
            <div class="captcha-container">
                <el-input
                    v-model="form.captcha"
                    :placeholder="t('login.captchaPlaceholder')"
                    maxlength="6"
                    clearable
                    class="captcha-input"
                ></el-input>
                <img
                    :src="captchaImage"
                    alt="验证码"
                    class="captcha-img"
                    @click="refreshCaptcha"
                    title="点击刷新验证码"
                />
            </div>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" style="width: 100%;" :loading="islogin" round @click="login">
                {{ t('login.signIn') }}
            </el-button>
        </el-form-item>
        <el-form-item style="margin-bottom: 10px;">
            <el-col :span="12">
                <div class="login-reg">
                    {{ t('login.noAccount') }}
                    <router-link to="/register">{{ t('login.createAccount') }}</router-link>
                </div>
            </el-col>
            <el-col :span="12" class="login-forgot">
                <router-link to="/password">{{ t('login.forgetPassword') }}？</router-link>
            </el-col>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox, type FormInstance, FormRules} from 'element-plus';
import {useI18n} from "vue-i18n";
import router from '@/router';
import {loginApi, getPolicyApi, logoutApi} from '@/api/modules/auth';
import {getCaptchaApi} from '@/api/modules/guest';
import {useAuthStore} from "@/store/modules/auth";
import {useMenuStore} from "@/store/modules/menu";
import {AuthRequestModel} from "@/models/authModel.ts";

const {t} = useI18n();
const authStore = useAuthStore();
const menuStore = useMenuStore();
const islogin = ref(false);
const captchaImage = ref();

const form = reactive<AuthRequestModel>({
    type: 'password',
    email: '',
    password: '',
    key: "",
    captcha: "",
});

const refreshCaptcha = async () => {
    const captchaData = await getCaptchaApi();
    captchaImage.value = captchaData.data.data.img;
    form.key = captchaData.data.data.key;
};

const rules = reactive<FormRules<AuthRequestModel>>({
    email: [
        {required: true, message: t('login.userError'), trigger: 'blur'}
    ],
    password: [
        {required: true, message: t('login.PWError'), trigger: 'blur'}
    ],
    captcha: [
        {required: true, message: t('login.captchaPlaceholder'), trigger: 'blur'}
    ],
})
const loginForm = ref<FormInstance>();

const login = async () => {
    const formInstance = loginForm.value;
    if (!formInstance) return;

    try {
        await formInstance.validate();
        islogin.value = true;
        const loginData = await loginApi(form);
        authStore.token = loginData.data.token;
        authStore.userInfo = loginData.data.user;

        let policyData = await getPolicyApi();
        if (policyData.data.menus.length === 0) {
            ElMessageBox.confirm('当前账户无任何菜单权限，请联系系统管理员!', '提示', {
                type: 'warning',
                confirmButtonClass: 'el-button--primary',
                showCancelButton: false,
            }).then(async () => {
                await logoutApi();
                authStore.$reset();
            });
            return;
        }
        menuStore.list = policyData.data.menus;
        menuStore.permissions = policyData.data.permissions;
        await router.replace({path: '/'});
        ElMessage.success("欢迎回来!");
    } catch (error) {
        await refreshCaptcha();
    } finally {
        islogin.value = false;
    }
};
onMounted(() => {
    refreshCaptcha();
});
</script>

<style>
.captcha-container {
    display: flex;
    align-items: center;
    width: 100%;
}

.captcha-input {
    flex: 1; /* 占满剩余宽度 */
    margin-right: 12px; /* 输入框和图片间距 */
    height: 40px; /* 和其他输入框高度一致 */
}

.captcha-input .el-input__inner {
    height: 40px; /* 控制输入框内容高度 */
    line-height: 40px;
    font-size: 14px;
    padding-left: 12px;
    box-sizing: border-box;
}

.captcha-img {
    width: 120px; /* 固定宽度 */
    height: 40px; /* 高度和输入框一致 */
    cursor: pointer;
    user-select: none;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    object-fit: cover;
    box-shadow: 0 0 6px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
}

.captcha-img:hover {
    box-shadow: 0 0 12px rgba(0, 0, 0, 0.25);
}
</style>
